package com.lepton.wifidog;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/auth/")
public class authHandle extends HttpServlet {
	private static final long serialVersionUID = 3L;
	
	public authHandle(){
		
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response){
		System.out.println("get method auth");
		String token = request.getParameter("token");
		String mac = request.getParameter("mac");
		String stage = request.getParameter("stage");
		if(token !=null && mac != null && isAccess(token, mac)){
			System.out.println("Auth: 1");
			
			try {
				if(stage.equals("logout")){
					response.getWriter().write("Auth: 0");
				}else{
					response.getWriter().write("Auth: 1");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				response.getWriter().write("Auth: 0");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return;
	}
	
	private boolean isAccess(String token, String mac) {
		// TODO Auto-generated method stub
		String str = "select mac from tokenMac where token = '" + token + "'";
		ResultSet st = mysqlHandle.getInstance().getResultSet(str);
		try {
			while(st.next()){
				if(st.getString("mac").equals(mac))
				{
					return true;
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response){
		System.out.println("post method auth");
	}
}
